package Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-09-07
 * Time: 12:34
 */

import java.util.LinkedList;
import java.util.Queue;

/**
 * 指的是 用普通的队列 来实现桟
 * 1. 模拟的入桟操作是：放到不为空的队列中
 * 2. 模拟的出栈操作是：把不为空的队列中的size-1个元素放到另外一个队列当中，最后剩下的这个就是我们模拟“出栈”的元素
 */
public class MyStackUseQueue {
    //创建两个队列：
    public Queue<Integer> qu1;
    public Queue<Integer> qu2;

    public MyStackUseQueue() {
        qu1 = new LinkedList<>();
        qu2 = new LinkedList<>();
    }

    public void push(int x) {
        if(!qu1.isEmpty()) {
            qu1.offer(x);
        } else if(!qu2.isEmpty()) {
            qu2.offer(x);
        } else {
            qu1.offer(x);
        }
    }

    public int pop() {
        if(empty()) {
            return -1;
        }
        if(!qu1.isEmpty()) {
            int sz = qu1.size();
            for (int i = 0; i < sz - 1; i++) {
                qu2.offer(qu1.poll());
            }
            return qu1.poll();
        } else {
            int sz = qu2.size();
            for (int i = 0; i < sz - 1; i++) {
                qu1.offer(qu2.poll());
            }
            return qu2.poll();
        }
    }

    public int top() {
        if(empty()) {
            return -1;
        }
        if(!qu1.isEmpty()) {
            int sz = qu1.size();
            int val = 0;
            for (int i = 0; i < sz; i++) {
                val = qu1.poll();
                qu2.offer(val);
            }
            return val;
        } else {
            int sz = qu2.size();
            int val = 0;
            for (int i = 0; i < sz; i++) {
                val = qu2.poll();
                qu1.offer(val);
            }
            return val;
        }
    }

    public boolean empty() {
        return qu1.isEmpty() && qu2.isEmpty();
    }

}
